package StackDemo;

import java.util.Scanner;
import java.util.Stack;

public class ScannerParenthesesValidation {
    public static boolean validateFormula(String formula) {
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < formula.length(); i++) {
            char c = formula.charAt(i);
            if (c == '(' || c == '{' || c == '[') {
                stack.push(c);
            } else if (c == ')' || c == '}' || c == ']') {
                if (stack.isEmpty()) {
                    return false;
                }
                char top = stack.pop();
                if ((c == ')' && top != '(') ||
                        (c == '}' && top != '{') ||
                        (c == ']' && top != '[')) {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        for (int i = 0; i < 5; i++) {
            System.out.println("请输入第 " + (i + 1) + " 个公式:");
            String inputFormula = scanner.nextLine();

            boolean result = validateFormula(inputFormula);
            if (result) {
                System.out.println("匹配成功");
            } else {
                System.out.println("匹配失败");
            }
        }

        scanner.close();
    }
}